module.exports = (app, router) => {
    const multer = require('multer')
    const fs = require('fs')
    const path = require('path')

    var storage = multer.diskStorage({
        destination: function (req, file, cb) {
            let ext = path.extname(file.originalname);
            let extArr = [ '.jpg', '.jpeg', '.gif', '.png', 'mp3'];
            if (!extArr.includes(ext)) {
                cb(new Error('扩展名不正确'));
            }
            const name = file.mimetype.includes('image') ? 'image' : 'music';
            let dir = `./uploads/${name}`
            //判断目录是否存在，没有则创建
            if (!fs.existsSync(dir)) {
                fs.mkdirSync(dir, {recursive: true});
            }
            cb(null, dir)
        },
        filename: function (req, file, cb) {
            let fileName = file.fieldname + '-' + Date.now() + path.extname(file.originalname);
            //fileName就是上传文件的文件名
            cb(null, fileName);
        }
    })
    const upload = multer({ storage })

    router.post('/upload', upload.any(), async (req, res, next) => {
        console.log(req.files[0])
        let url = (__dirname + req.files[0].path).replace(/\\/g,"\/");
        res.send({
            status: 1,
            data: {
                url,
                name: req.files[0].originalname
            }
        })
    })
    //捕获错误
    app.use(function (err, req, res, next) {
        res.send({
            status: 1,
            message: err.toString()
        });
    });

    app.use('/admin/api', router)
}